import { BadRequestException, Injectable } from '@nestjs/common';
import { FindOptionsWhere, In, Like, Repository } from 'typeorm';
import { RoleManage } from './entities/roleManage.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { CreateRoleDto } from './dto/create.dto';
import { UpdateRoleDto } from './dto/update.dto';
import { DeleteRoleDto } from './dto/delete.dto';
import { ListDto } from './dto/list.dto';
import { MenuManage } from '../menuManage/entities/menuManage.entity';

@Injectable()
export class RoleManageService {
  @InjectRepository(RoleManage)
  private readonly RoleManageRepository: Repository<RoleManage>;

  @InjectRepository(MenuManage)
  private readonly MenuManageRepository: Repository<MenuManage>;

  async createRole(role: CreateRoleDto) {
    const isExist = await this.RoleManageRepository.findOne({
      where: { name: role.name },
    });
    if (isExist) {
      throw new BadRequestException('角色名称已存在');
    }

    if (role?.menus) {
      const menus = await this.MenuManageRepository.findBy({
        id: In(role.menus),
      });
      role.menus = menus;
    }
    return await this.RoleManageRepository.save(role);
  }

  async deleteRole(deleteRoleDto: DeleteRoleDto) {
    const isExist = await this.RoleManageRepository.findOne({
      where: { id: deleteRoleDto.id },
    });
    if (!isExist) {
      throw new BadRequestException('角色不存在');
    }
    return await this.RoleManageRepository.delete(deleteRoleDto.id);
  }

  async updateRole(Role: UpdateRoleDto) {
    const isExist = await this.RoleManageRepository.findOne({
      where: { id: Role.id },
    });
    if (!isExist) {
      throw new BadRequestException('角色不存在');
    }
    if (Role?.menus) {
      const menus = await this.MenuManageRepository.findBy({
        id: In(Role.menus),
      });
      console.log(menus);
      Role.menus = menus;
    }
    return await this.RoleManageRepository.save(Role);
  }

  async getDetail(params: Partial<RoleManage>) {
    return await this.RoleManageRepository.find({
      where: params,
      relations: ['menus', 'userRoles'],
    });
  }

  async getMenuList(listDto: ListDto) {
    const { page, limit, name, ...resetListDto } = listDto;
    const query: FindOptionsWhere<Omit<ListDto, 'page' | 'limit'>> =
      resetListDto;
    if (name) {
      query.name = Like(`%${name}%`);
    }

    const [list, total] = await this.RoleManageRepository.findAndCount({
      where: query,
      skip: (page - 1) * limit,
      take: limit,
      relations: ['menus', 'userRoles'],
    });
    return {
      list,
      total,
      page,
      limit,
    };
  }
}
